package com.zhongfeng.api.modules.utils.file;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @author blueCat
 * @date 2023/2/27 16:24
 * @motto life is a gift
 */
public class ImgUtil {

    /**
     * 获取图片文件流
     * @param image
     * @return
     */
    public static BufferedImage toBufferedImage(Image image){
        if (image instanceof BufferedImage){
            return (BufferedImage) image;
        }
        image = new ImageIcon(image).getImage();
        BufferedImage bImage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bImage = gc.createCompatibleImage(image.getWidth(null),image.getHeight(null),transparency);
        } catch (HeadlessException e) {
        }
        if (bImage == null){
            int type = BufferedImage.TYPE_INT_RGB;
            bImage = new BufferedImage(image.getWidth(null),image.getHeight(null),type);
        }
        Graphics g = bImage.createGraphics();
        g.drawImage(image,0,0,null);
        g.dispose();
        return bImage;
    }
}
